import React, { useState } from 'react';
import { Button } from 'antd';
import { CopyOutlined, CheckOutlined } from '@ant-design/icons';
import ReactMarkdown from 'react-markdown';
import rehypeRaw from 'rehype-raw';
import rehypeHighlight from 'rehype-highlight';
import 'highlight.js/styles/github-dark.css'; // 使用深色主题
import './index.less';

interface MarkdownCodeBlockProps {
  code: string;
}

const MarkdownCodeBlock: React.FC<MarkdownCodeBlockProps> = ({ code }) => {
  const [copiedText, setCopiedText] = useState(false);

  const copyCode = async () => {
    try {
      if (navigator.clipboard) {
        await navigator.clipboard.writeText(code);
      } else {
        const textArea = document.createElement('textarea');
        textArea.value = code;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
      }

      setCopiedText(true);
      setTimeout(() => setCopiedText(false), 2000);
    } catch (err) {
      console.error('Copy failed:', err);
    }
  };

  return (
    <div className="code-block">
      <div className="code-header">
        <span>代码预览</span>
        <Button
          type="text"
          icon={copiedText ? <CheckOutlined /> : <CopyOutlined />}
          onClick={copyCode}
          className={`copy-button ${copiedText ? 'copied' : ''}`}
        >
          {copiedText ? '已复制' : '复制代码'}
        </Button>
      </div>
      <div className="code-container">
        <ReactMarkdown rehypePlugins={[rehypeRaw, rehypeHighlight]} className="code-content">
          {`\`\`\`tsx
${code}`}
        </ReactMarkdown>
      </div>
    </div>
  );
};

export default MarkdownCodeBlock;
